package com.significantfiles.snapshot.engine.tx;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.significantfiles.snapshot.engine.util.Utils;

public class TransactionPersistentObject implements Serializable {

	public TransactionPersistentObject(final Transaction<?> tx) throws TransactionSerializationException {
		if (tx == null)
			throw new NullPointerException( "parameter:tx" );

		this.className = tx.getClass().getName();
		this.version = tx.getVersion();
		
		final ByteArrayOutputStream buffer = new ByteArrayOutputStream( 1024 );
		writeTxToBuffer(tx, buffer);
		
		this.classCode = buffer.toByteArray();
	}

	private void writeTxToBuffer(final Transaction<?> tx,
			final ByteArrayOutputStream buffer)
			throws TransactionSerializationException {
		final ObjectOutputStream out = getOutputStream(buffer);
		
		try {
			out.writeObject( tx );
			out.flush();
		} catch (final IOException e) {
		} finally {
			Utils.closeStream(out);
		}
	}

	private ObjectOutputStream getOutputStream(
			final ByteArrayOutputStream buffer) throws TransactionSerializationException {
		try {
			return new ObjectOutputStream( buffer );
		} catch (final IOException e) {
			throw new TransactionSerializationException( e );
		}
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private final String className;

	private final byte[] classCode;

	private final long version;

	public byte[] getClassCode() {
		return classCode;
	}

	public String getClassName() {
		return className;
	}

	public long getVersion() {
		return version;
	}

}
